package ch.ffhs.esma.bunk_weiss.notepad;

/**
 * @author: Tobias Weiss/Julian Bunk
 * @Date: 04.01.2015
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class SynchronizeServer extends Activity implements OnClickListener {
	
	private static final int DISCOVERABLE_REQUEST_CODE = 0x1;
	private boolean CONTINUE_READ_WRITE = true;
	private TextView state;
	private TextView input;
	private TextView output;
	private int nbr = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.synchronize_note_activity);
		
		// Back to Main-Menu
		View verwerfen = findViewById(R.id.backtomain);
		verwerfen.setOnClickListener(this);
		
		//Always make sure that Bluetooth server is discoverable during listening...
		
		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		startActivityForResult(discoverableIntent, DISCOVERABLE_REQUEST_CODE);
		state = (TextView) findViewById(R.id.state);
		state.setText("DISCOVERABLE_REQUEST_CODE");
		input = (TextView) findViewById(R.id.receive);
		input.setText("Read: ");
		output = (TextView) findViewById(R.id.send);
		output.setText("Sent: ");
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		state.setText("WARTE");
		new Thread(reader).start();
	}
	
	public void onSend(View v){
		String msg = "Message From Server " + (nbr++) + "\n";
		try{
			output.setText("Sent: " + msg);
			os.write(msg);
			os.flush();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onDestroy() {
		try{
			os.write("!end!");
			os.flush();
		}catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
		if(socket != null){
			try{
				is.close();
				os.close();
				socket.close();
			}catch(Exception e){}
			CONTINUE_READ_WRITE = false;
		}
	}
	
	
	
	private BluetoothSocket socket;
	private InputStream is;
	private OutputStreamWriter os;
	private Runnable reader = new Runnable() {
		public void run() {
			BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
			UUID uuid = UUID.fromString("4e5d48e0-75df-11e3-981f-0800200c9a66");
			try {
				BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("BLTServer", uuid);				
				socket = serverSocket.accept();

				is = socket.getInputStream();
				os = new OutputStreamWriter(socket.getOutputStream());

				
				int bufferSize = 1024;
				int bytesRead = -1;
				byte[] buffer = new byte[bufferSize];
				//Keep reading the messages while connection is open...
				while(CONTINUE_READ_WRITE){
					final StringBuilder sb = new StringBuilder();
					bytesRead = is.read(buffer);
					if (bytesRead != -1) {
					String result = "";
					while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){
						result = result + new String(buffer, 0, bytesRead - 1);
						bytesRead = is.read(buffer);
						}
						result = result + new String(buffer, 0, bytesRead - 1);
						sb.append(result);
					}
					
					//Show message on UIThread
					runOnUiThread(new Runnable() {	
						@Override
						public void run() {
							input.setText("Read: " + sb.toString());
						}
					});
				}
			} catch (IOException e) {e.printStackTrace();}
		}
	};
	
	@Override
	public void onClick(View arg0) {
		if (arg0.getId() == R.id.backtomain) {

			// define a new Intent for the Home Activity
			Intent intent = new Intent(this, Home.class);

			// start the Home Activity
			this.startActivity(intent);
			finish();
		}
	}
	
}
